import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {message} from "antd";
import {reqAdminLogin} from "../../api/backStage/backStageApi";
import {getAdminToken, setAdminToken} from "../../utils/adminToken";


export const adminLogin = createAsyncThunk(
    'user/adminLoginStatus',
    async ({adminInfo}) => {
        const data = await reqAdminLogin({fd: adminInfo})
        return data
    }
)


const adminLoginSlice = createSlice({
    name: 'adminLogin',
    initialState: {
        adminAllInfo: {},
        admin_token: getAdminToken()
    },
    reducers: {
        logout(state, action) {
            state.admin_token = null
        },
        updateAdminInfo(state, action) {
            state.adminAllInfo = action.payload
        }
    },
    extraReducers: builder => {
        //登录成功后的方法
        builder.addCase(adminLogin.fulfilled, (state, action) => {
            const {status, token, admin} = action.payload
            try {
                state.adminAllInfo = {...admin}
                state.admin_token = token
                if (status !== 0) {
                    message.error("未找到该管理员!")
                } else if (status === 0) {
                    //设置token值
                    setAdminToken(state.admin_token)
                    message.info("管理员登录成功了!")
                }
            } catch (e) {
                message.error(e)
            }
        })
    }
})

export const {logout,updateAdminInfo} = adminLoginSlice.actions
export const {reducer: adminLoginReducer} = adminLoginSlice